// server.cpp
#include "command.h"

// server端做读端

int main()
{
    bool r = createNamedPipe(PIPE_NAME);
    assert(r == true);
    (void)r;

    // 如果client端没有打开管道
    // 那么open将阻塞
    int rfd = open(PIPE_NAME,O_RDONLY);//只读方式打开

    if(rfd < 0)
    {
        exit(1);
    }

    char buffer[1024] = {0};
    while(true)
    {
        // 从管道中读取数据到buffer
        int n = read(rfd,buffer,sizeof(buffer)-1);
        if(n > 0)//read的返回值为读取到多少数据
        {
            buffer[n] = 0;
            std::cout << "client->server say #" << buffer << std::endl;
        }
        else if(n == 0)//如果数据为0，说明写端关闭
        {
            std::cout << "client quit, me too!" << std::endl;
            break;
        }
    }
    
    close(rfd);
    closeNamedPipe(PIPE_NAME);
    return 0;
}